package com.xs.dbs;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author xs
 * date 2019-04-29 10:47
 */
@Configuration
@MapperScan(basePackages="com.xs.dao", sqlSessionFactoryRef="sessionFactory")
public class MybatisConfig {
    @Autowired
    Environment environment;

    @Value("${datasource.jdbc.driverClassName}")
    private String dbDriver;

    @Value("${datasource.jdbc.url}")
    private String dbUrl;

    @Value("${datasource.jdbc.username}")
    private String dbUsername;

    @Value("${datasource.jdbc.password}")
    private String dbPassword;

    @Value("${datasource.jdbc.url_stg}")
    private String dbUrl_stg;

    @Value("${datasource.jdbc.username_stg}")
    private String dbUsername_stg;

    @Value("${datasource.jdbc.password_stg}")
    private String dbPassword_stg;


    /**
     * 创建 local环境 dataSource
     */
    @Bean(name="dataSourceFunctional")
    public DataSource dataSourceLocal() {
        HikariConfig config = new HikariConfig();
        config.setDriverClassName(dbDriver);
        config.setJdbcUrl(dbUrl); //数据源
        config.setUsername(dbUsername); //用户名
        config.setPassword(dbPassword); //密码
        HikariDataSource dataSource = new HikariDataSource(config);
        return dataSource;
    }

    /**
     * 创建 回归环境 dataSource
     */
    @Bean(name="dataSourceRegression")
    public DataSource dataSourceStaging() {
        HikariConfig config = new HikariConfig();
        config.setDriverClassName(dbDriver);
        config.setJdbcUrl(dbUrl_stg); //数据源
        config.setUsername(dbUsername_stg); //用户名
        config.setPassword(dbPassword_stg); //密码
        HikariDataSource dataSource = new HikariDataSource(config);
        return dataSource;
    }

    /**
     * 1、创建动态数据源
     * @throws Exception
     * @Primary该注解表示在同一个接口有多个类可以注入的时候，默认选择哪个，而不是让@Autowired报错
     */
    @Bean(name="dynamicDataSource")
//    @Primary
    public DynamicDataSource DataSource(@Qualifier("dataSourceFunctional") DataSource dataSourceFunctional,
                                        @Qualifier("dataSourceRegression") DataSource dataSourceRegression){
        Map<Object, Object> targetDataSource = new HashMap<>();
        targetDataSource.put(DatabaseType.Seven_Day, dataSourceFunctional);
        targetDataSource.put(DatabaseType.Li_Feng, dataSourceRegression);
        DynamicDataSource dataSource = new DynamicDataSource();
        dataSource.setTargetDataSources(targetDataSource);
        //设置默认数据源
        dataSource.setDefaultTargetDataSource(dataSourceFunctional);
        return dataSource;
    }



    /**
     * 2、根据数据源创建SqlSessionFactory
     * @throws Exception
     */
    @Bean(name="sessionFactory")
    public SqlSessionFactory sessionFactory(@Qualifier("dynamicDataSource")DynamicDataSource dataSource) throws Exception{
        SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(dataSource);
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        sessionFactoryBean.setMapperLocations(resolver.getResources(environment.getProperty("mybatis.mapperLocations")));    //*Mapper.xml位置

        // 设置MyBatis分页插件
//        PageInterceptor pageInterceptor = this.initPageInterceptor();
//        sessionFactoryBean.setPlugins(new Interceptor[]{pageInterceptor});
        return sessionFactoryBean.getObject();
    }


    /**
     * 配置事务管理器 （一定要配置 不然注解事务会失效的！！！）
     */
    @Bean
    public DataSourceTransactionManager transactionManager(DynamicDataSource dataSource) throws Exception {
        return new DataSourceTransactionManager(dataSource);
    }

}
